<template>
  <Header title="购物车" class="cart-header"></Header>
  <div class="cart-wrapper">
    <!-- v-molde 双向绑定 :name=item.carItemId -->
    <van-checkbox-group v-model="state.result" ref="checkboxGroup" @change="groupChange">
      <van-swipe-cell v-for="item in state.cartList" :key="cartItemId">
        <van-checkbox :name="item.cartItemId"></van-checkbox>
        <van-card :price="item.sellingPrice" :title="item.goodsName" class="goods-card" :thumb="item.goodsCoverImg">
          <template #footer>
            <van-stepper v-model="item.goodsCount" min="1" max="5" @change="onChange" :name="item.cartItemId" />
            <!-- 绑定:name="item.cartItemId" 让后端知道我购物车加商品数量，加的是那个商品 -->
          </template>
        </van-card>
        <template #right>
          <van-button @click="deleteGoods(item.cartItemId)" square text="删除" type="danger" class="delete-button" />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>
  </div>

  <!-- all -->
  <van-submit-bar :price="totalPrice * 100" button-text="提交订单" @submit="onSubmit" class="submit-all">
    <van-checkbox class="check-all" v-model="state.checkedAll" @click="allCheck">全选</van-checkbox>
  </van-submit-bar>
  <NavBar></NavBar>
</template>

<script setup>
import { reactive } from 'vue';
import Header from '../components/Header.vue';
import NavBar from '../components/NavBar.vue';
import { getCart, deleteCartItem } from '../api/service/cart.js';
import { onMounted } from 'vue';
import { modifyCart } from '../api/service/cart.js'
import { showLoadingToast, closeToast,showFailToast  } from 'vant';
import { computed } from 'vue';
import useCartStore from '@/store/cart.js'
import {useRouter} from 'vue-router';
const router=useRouter()
const cartStore = useCartStore() //仓库

const state = reactive({
  result: [],
  cartList: [],  //购物车数据
  checkedAll: false
})

//得到用户购物车的信息
onMounted(() => {
  init()
})
const init = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  });
  const { data } = await getCart({ pageNumber: 1 })
  console.log(data);
  state.cartList = data
  closeToast()
}

//点击加减，以至于刷新页面时，不会让页面的商品数量丢失，让商品同步
const onChange = async (value, detail) => {
  showLoadingToast({
    message: '修改中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  });
  const params = {
    cartItemId: detail.name,
    goodsCount: value
  }
  await modifyCart(params)   //修改商品购买的数量
  closeToast()
  // console.log(value, detail);
}

//计算总金额
const totalPrice = computed(() => {
  let sum = 0
  let _list = state.cartList.filter(item => state.result.includes(item.cartItemId))
  //筛选勾选商品，购物车中哪些是被选的商品  循环被勾选的数据 数量乘与金额
  // console.log(_list);
  _list.forEach(item => { sum += item.sellingPrice * item.goodsCount })
  return sum
})

//全选的状态
const allCheck = () => {
  if (!state.checkedAll) {  //空 全不选
    state.result = []
  } else {
    state.result = state.cartList.map(item => item.cartItemId)
  }
}

const groupChange = (result) => {
  state.checkedAll = result.length === state.cartList.length ? true : false
}

//删除按钮，删除购物车数据，发接口请求，删除那条数据,异步代码
const deleteGoods = async (id) => {
  await deleteCartItem(id)
  cartStore.initBadge()
  init()  //刷新数据
}

//跳转页面到 生成订单页面
const onSubmit=()=>{
  if (state.result.length===0) {
    showFailToast('请选择商品进行结算')
    return
  }
    router.push({path:'/create-order',query:{cartItemIds:state.result}})
  
}
</script>

<style lang="less" scoped>
.cart-header {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
}

.cart-wrapper {
  padding-top: 50px;
  padding-bottom: 110px;
}

.goods-card {
  margin: 0;
  background-color: #fff;
}

.delete-button {
  height: 100%;
}
</style>


 
<style lang="less">
.van-swipe-cell__wrapper {
  display: flex;
  padding-left: 15px;

}

.van-checkbox {
  width: 22px;
}

.goods-card {
  flex: 1;
}

.van-card__footer {
  position: absolute;
  right: 16px;
  bottom: 8px;
}

.van-card__price {
  color: red;
  font-size: 16px;
}

.submit-all {
  bottom: 50px;
  // !important 最高权重
}

.check-all {
  width: 60px;

}
</style>